#include "StdAfx.h"
#include "Machine.h"
#include "MachineFinishedMsg.h"

Machine::Machine(Communicator & com, ID nestID, ID machineID, Parameters * distribution):currentTask(NULL),Actor(com),nestID(nestID),machineID(machineID),distribution(distribution)
{  
}

Machine::~Machine(void)
{
}

bool Machine::isEmpty()
{
	return currentTask == NULL;
}

void Machine::tick()
{
	//if(!isEmpty() && remainingTime>0){
	//	remainingTime--;
	//	if(remainingTime == 0){
	//		com.addMesage(new MachineFinishedMsg(com.currentTime,nestID,machineID));
	//	}
	//}

	if(!isEmpty())
	{
		if(remainingTime>0)
		{
			remainingTime--;
			if(remainingTime == 0)
			{
				com.addMesage(new MachineFinishedMsg(com.currentTime,nestID,machineID));
			}
			currentTask->incWorking();
		} else {
			currentTask->incWaiting();
		}
	}
}

bool Machine::assignTask( Task * task )
{
	if(currentTask == NULL){
		currentTask = task;
		remainingTime = (*distribution)();
		return true;
	} else {
		return false;
	}
}

bool Machine::returnTask(Task **out_task)
{
	*out_task = NULL;
	if ( currentTask==NULL ){
		return true;
	} else {
		if (remainingTime == 0)
		{
			*out_task = currentTask;
			currentTask = NULL;
			return true;
		} 
		else
		{
			return false;
		}
	}
}

bool Machine::hasFinished()
{
	if(currentTask != NULL && remainingTime == 0){
		return true;
	} else {
		return false;
	}
}
